import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ugrownews_flutter/login/ScreenSelfCenter.dart';
import 'package:ugrownews_flutter/main/ScreenSearch.dart';
import 'package:ugrownews_flutter/main/fragment/FragmentMainLive.dart';
import 'package:ugrownews_flutter/main/fragment/FragmentMainNews.dart';
import 'package:ugrownews_flutter/main/fragment/FragmentMainRequest.dart';
import 'package:ugrownews_flutter/utils/RouterUtil.dart';
import 'package:ugrownews_flutter/utils/Toast.dart';
import 'package:ugrownews_flutter/utils/UGrowColors.dart';
import 'package:ugrownews_flutter/utils/jpush_flutter.dart';

///
/// ScreenMain
/// APP主页
///
///

class ScreenMain extends StatefulWidget {
  @override
  _ScreenMainState createState() => _ScreenMainState();
}

class _ScreenMainState extends State<ScreenMain>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  TabController tabController;
  int _index = 0;
  int backTime = 0;
  bool isJpushInited = false;

  @override
  void initState() {
    super.initState();
    //设置通知栏文字颜色为黑色,需要改动的时候才需要修改，不改动会一直继承前边页面的颜色
    if (Platform.isAndroid) {
      SystemUiOverlayStyle systemUiOverlayStyle = new SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.dark,
          statusBarBrightness: Brightness.dark);
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }
    //初始化tab控制，并监听tab，用于修改下方导航按钮。
    tabController = new TabController(length: 3, vsync: this);
    tabController.addListener(() {
      if (tabController.index < 3) {
        setState(() {
          _index = tabController.index;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // 初始化极光推送,
    // 以首页的context作为推送跳转用的context，
    // 理论上首页的context 不会消失

    RouterUtil.setContexdt(context);
    if (!isJpushInited) {
      _initJpush(context);
      isJpushInited = true;
    }

    //WillPopScope  用于监听返回按键，
    return new WillPopScope(
      child: new Scaffold(
        body: new Stack(
          children: <Widget>[
            new Stack(
              children: <Widget>[
                getTopView(),
                //中间主体部分
                getMidView(),
                //底部导航栏
                getBottomVeiw(),
                //更新了1.5之后，tabvarview 和 tabbar 的子view个数必须相等
                //所以单独提出来"我的"
                getMineView(),
              ],
            )
          ],
        ),
      ),
      onWillPop: () {
        //监听返回按钮
        if (new DateTime.now().millisecondsSinceEpoch - backTime > 3000) {
          backTime = new DateTime.now().millisecondsSinceEpoch;
          Toast.toast(context, "再按一次返回");
        } else {
          return new Future.value(true);
        }
      },
    );
  }

  Widget getTopView() {
    //顶部导航，包含通知栏高度
    return new Positioned(
      height: ScreenUtil.instance.setWidth(118) +
          MediaQuery.of(context).padding.top,
      width: ScreenUtil.screenWidthDp,
      child: new Container(
        color: UGrowColors.getColor("#dff1fd"),
        child: new Stack(
          alignment: Alignment.center,
          children: <Widget>[
            //渐变背景
            new Container(
              margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
              width: ScreenUtil.screenWidthDp,
              height: ScreenUtil.instance.setWidth(118),
              decoration: new BoxDecoration(
                  gradient: new LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                    UGrowColors.getColor("#dff1fd"),
                    UGrowColors.getColor("#84dce6"),
                  ])),
            ),
            // 搜索按钮
            // 包了一层是为了让点击事件触发更灵敏
            new Positioned(
              left: 0,
              top: MediaQuery.of(context).padding.top,
              height: ScreenUtil.getInstance().setWidth(118),
              width: ScreenUtil.getInstance().setWidth(140),
              child: new GestureDetector(
                child: new Container(
                  padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(40),
                    ScreenUtil.getInstance().setWidth(27),
                    ScreenUtil.getInstance().setWidth(35),
                    ScreenUtil.getInstance().setWidth(27),
                  ),
                  child: new Image.asset(
                    "images/live_search.png",
                    fit: BoxFit.fill,
                  ),
                ),
                onTap: () {
                  Navigator.of(context)
                      .push(new CupertinoPageRoute(builder: (context) {
                    return new ScreenSearch();
                  }));
                },
              ),
            ),
            //中间图标
            new Container(
              margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
              width: ScreenUtil.getInstance().setWidth(124),
              height: ScreenUtil.getInstance().setWidth(66),
              child: new Image.asset(
                "images/main_logo.png",
                fit: BoxFit.fill,
              ),
            ),
            // 右侧个人中心
            // 包了一层是为了让点击事件触发更灵敏
            new Positioned(
              left: ScreenUtil.screenWidthDp -
                  ScreenUtil.getInstance().setWidth(140),
              top: MediaQuery.of(context).padding.top,
              height: ScreenUtil.getInstance().setWidth(118),
              width: ScreenUtil.getInstance().setWidth(140),
              child: new GestureDetector(
                child: new Container(
                  padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(40),
                    ScreenUtil.getInstance().setWidth(27),
                    ScreenUtil.getInstance().setWidth(40),
                    ScreenUtil.getInstance().setWidth(27),
                  ),
                  child: new Image.asset(
                    "images/main_mine_logo.png",
                    fit: BoxFit.fill,
                  ),
                ),
                onTap: () {
                  Navigator.of(context).push(
                    new CupertinoPageRoute(
                      builder: (context) {
                        return new ScreenSelfCenter();
                      },
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget getMidView() {
    return new Positioned(
      top: MediaQuery.of(context).padding.top +
          ScreenUtil.instance.setWidth(118),
      height: ScreenUtil.screenHeightDp -
          MediaQuery.of(context).padding.top -
          MediaQuery.of(context).padding.bottom -
          ScreenUtil.instance.setWidth(118) -
          ScreenUtil.instance.setWidth(180),
      width: ScreenUtil.screenWidthDp,
      child: new TabBarView(
        controller: tabController,
        children: <Widget>[
          //四个Fragment，
          new FragmentMainNews(),
          new FragmentMainLive(),
          new FragmentMainRequest(),
        ],
      ),
    );
  }

  Widget getBottomVeiw() {
    return new Container(
      color: Colors.white,
      margin: new EdgeInsets.fromLTRB(
          0,
          ScreenUtil.screenHeightDp -
              ScreenUtil.instance.setWidth(180) -
              MediaQuery.of(context).padding.bottom,
          ScreenUtil.screenWidthDp / 4,
          MediaQuery.of(context).padding.bottom),
      height: ScreenUtil.instance.setWidth(180),
      child: new TabBar(
        indicatorWeight: 0.0001,
        indicatorSize: TabBarIndicatorSize.tab,
        controller: tabController,
        onTap: (index) {
          setState(() {
            _index = index;
          });
        },
        tabs: [
          new Container(
            height: ScreenUtil.instance.setWidth(180),
            width: ScreenUtil.screenWidthDp / 4,
            color: Colors.white,
            alignment: Alignment.center,
            child: new Column(
              children: <Widget>[
                new Container(
                  child: new Image.asset(_index == 0
                      ? "images/main_bottom_xinwen1.png"
                      : "images/main_bottom_xinwen2.png"),
                  height: ScreenUtil.instance.setWidth(100),
                  margin: new EdgeInsets.all(ScreenUtil.instance.setWidth(10)),
                ),
                new Container(
                  child: new Text(
                    "新闻",
                    style: new TextStyle(
                      fontSize: ScreenUtil.instance.setWidth(40),
                      color: _index == 0
                          ? UGrowColors.getColor("#2c1a70")
                          : UGrowColors.getColor("#5d5d5d"),
                    ),
                  ),
                ),
              ],
            ),
          ),
          new Container(
            height: ScreenUtil.instance.setWidth(180),
            width: ScreenUtil.screenWidthDp / 4,
            color: Colors.white,
            alignment: Alignment.center,
            child: new Column(
              children: <Widget>[
                new Container(
                  child: new Image.asset(_index == 1
                      ? "images/main_bottom_zhibo1.png"
                      : "images/main_bottom_zhibo2.png"),
                  height: ScreenUtil.instance.setWidth(100),
                  margin: new EdgeInsets.all(ScreenUtil.instance.setWidth(10)),
                ),
                new Container(
                  child: new Text(
                    "直播",
                    style: new TextStyle(
                      fontSize: ScreenUtil.instance.setWidth(40),
                      color: _index == 1
                          ? UGrowColors.getColor("#2c1a70")
                          : UGrowColors.getColor("#5d5d5d"),
                    ),
                  ),
                ),
              ],
            ),
          ),
          new Container(
            height: ScreenUtil.instance.setWidth(180),
            width: ScreenUtil.screenWidthDp / 4,
            color: Colors.white,
            alignment: Alignment.center,
            child: new Column(
              children: <Widget>[
                new Container(
                  child: new Image.asset(_index == 2
                      ? "images/main_bottom_dianbo1.png"
                      : "images/main_bottom_dianbo2.png"),
                  height: ScreenUtil.instance.setWidth(100),
                  margin: new EdgeInsets.all(ScreenUtil.instance.setWidth(10)),
                ),
                new Container(
                  child: new Text(
                    "点播",
                    style: new TextStyle(
                      fontSize: ScreenUtil.instance.setWidth(40),
                      color: _index == 2
                          ? UGrowColors.getColor("#2c1a70")
                          : UGrowColors.getColor("#5d5d5d"),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget getMineView() {
    return new Container(
      color: Colors.white,
      margin: new EdgeInsets.fromLTRB(
          ScreenUtil.screenWidthDp * 3 / 4,
          ScreenUtil.screenHeightDp -
              ScreenUtil.instance.setWidth(180) -
              MediaQuery.of(context).padding.bottom,
          0,
          MediaQuery.of(context).padding.bottom),
      height: ScreenUtil.instance.setWidth(180),
      child: new GestureDetector(
        child: new Container(
          height: ScreenUtil.instance.setWidth(180),
          width: ScreenUtil.screenWidthDp / 4,
          color: Colors.white,
          alignment: Alignment.center,
          child: new Column(
            children: <Widget>[
              new Container(
                child: new Image.asset(_index == 3
                    ? "images/main_bottom_huodong1.png"
                    : "images/main_bottom_huodong2.png"),
                height: ScreenUtil.instance.setWidth(100),
                margin: new EdgeInsets.all(ScreenUtil.instance.setWidth(10)),
              ),
              new Container(
                child: new Text(
                  "我的",
                  style: new TextStyle(
                    fontSize: ScreenUtil.instance.setWidth(40),
                    color: _index == 3
                        ? UGrowColors.getColor("#2c1a70")
                        : UGrowColors.getColor("#5d5d5d"),
                  ),
                ),
              ),
            ],
          ),
        ),
        onTap: () {
          Navigator.of(context).push(
            new CupertinoPageRoute(
              builder: (context) {
                return new ScreenSelfCenter();
              },
            ),
          );
        },
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

void _initJpush(BuildContext context) async {
  JPush jPush = new JPush();

  jPush.getLaunchAppNotification().then((map) {
    if (map != null && map.length > 0) {
      if (Platform.isIOS) {
        String id = map["extras"]["content"].toString();
        RouterUtil.navigateToForPush(
          RouterUtil.ROUTER_NEWSDETAIL + "?id=" + id,
        );
        jPush.setBadge(0);
      } else if (Platform.isAndroid) {
        Map params =
        json.decode(map["extras"]["cn.jpush.android.EXTRA"].toString());
        String id = params["content"].toString();
        RouterUtil.navigateToForPush(
          RouterUtil.ROUTER_NEWSDETAIL + "?id=" + id,
        );
      }
      jPush.setBadge(0);
    }
  });
  jPush.addEventHandler(
    // 接收通知回调方法。
    onReceiveNotification: (Map<String, dynamic> message) async {},
    // 点击通知回调方法。
    onOpenNotification: (Map<String, dynamic> message) async {
      print("isIOS");
      if (Platform.isIOS) {
        print("isIOS true");
        String id = message["extras"]["content"].toString();
        RouterUtil.navigateToForPush(
          RouterUtil.ROUTER_NEWSDETAIL + "?id=" + id,
        );
        jPush.setBadge(0);
      } else if (Platform.isAndroid) {
        print("isAndroid true");
        Map params =
        json.decode(message["extras"]["cn.jpush.android.EXTRA"].toString());
        String id = params["content"].toString();
        RouterUtil.navigateToForPush(
          RouterUtil.ROUTER_NEWSDETAIL + "?id=" + id,
        );
      }
    },
    // 接收自定义消息回调方法。
    onReceiveMessage: (Map<String, dynamic> message) async {},
  );

  jPush.setup(
    appKey: "af16b7ae82272b539ca5b45b",
    channel: "theChannel",
    production: false,
    debug: true, // 设置是否打印 debug 日志
  );
  jPush.applyPushAuthority(
      new NotificationSettingsIOS(sound: true, alert: true, badge: true));
}
